Operators and Default Streams

Contents|Index|Previous|Next
Operators and default streams

The GNU Iostream library, libio, implements the standard input and output facilities for C++. These facilities are roughly analogous (in their purpose and ubiquity, at least) with those defined by the C stdio functions.

Although these definitions come from a library, rather than being part of the core language,” they are sufficiently central to be specified in the latest draft standard for C++.

You can use two operators defined in this library for basic input and output operations. They are familiar from any C++ introductory text-book: << for output, and >> for input. (Think of data flowing in the direction of the “arrows.”)

These operators are often used in conjunction with the following three streams that are open by default.

- ostream cout
  Variable
The standard output stream, analogous to the C stdout.
- ostream cin
  Variable
The standard input stream, analogous to the C stdin.
- ostream cerr
  Variable
An alternative output stream for errors, analogous to the C stderr.
For example, the following example shows a bare-bones C++ version of the traditional “hello” program using << and cout.

    #include <iostream.h>

    int main(int argc, char **argv)
    {
       cout << "Well, hi there.\n";
       return 0;
    }

Casual use of these operators may be seductive, but—other than in writing throwaway code for your own use—it is not necessarily simpler than managing input and output in any other language. For example, robust code should check the state of the input and output streams between operations (for example, using the method, good). See also Checking the state of a stream. You may also need to adjust maximum input or output field widths, using manipulators like setw or setprecision.

<<
Operator on ostream

Write output to an open output stream of class, ostream. Defined by this library on any object of a C++ primitive type, and on other classes of the library. You can overload the definition for any of your own applications’ classes.

Returns a reference to the implied argument, *this (the open stream it writes on), permitting multiple inputs like the following statement.

    cout << "The value of i is " << i << "\n";

>>
Operator on istream

Read input from an open input stream of class, istream. Defined by this library on primitive numeric, pointer, and string types; you can extend the definition for any of your own applications’ classes.

Returns a reference to the implied argument, *this (the open stream it reads), permitting multiple inputs in one statement.

Top|Contents|Index|Previous|Next